package org.clxmm.security.springmvc.controller;

import org.clxmm.security.springmvc.model.AuthenticationRequest;
import org.clxmm.security.springmvc.model.UserDto;
import org.clxmm.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;


/**
 * @author clxmm
 * @Description
 * @create 2021-06-06 6:04 下午
 */
@RestController
public class LoginController {


    @Autowired
    AuthenticationService authenticationService;

    //    @PostMapping(value = "/login",produces = {"text/plain;charset=UTF‐8"} )
//    @PostMapping(value = "/login")
    public String login(AuthenticationRequest authenticationRequest) {


        UserDto userDto = authenticationService.authentication(authenticationRequest);


        return userDto.getUsername() + " success ";
    }


    /**
     * 用户登录
     *
     * @param authenticationRequest 登录请求
     * @param session               http会话
     * @return
     */
    @PostMapping(value = "/login")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {

        UserDto userDto = authenticationService.authentication(authenticationRequest);
        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);
        return userDto.getUsername() + "登录成功";

    }


    @GetMapping(value = "logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "退出成功";
    }


    /**
     * 测试资源1
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1")
    public String r1(HttpSession session) {
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullname = ((UserDto) userObj).getFullname();
        } else {
            fullname = "匿名";
        }
        return fullname + " success 1";
    }

    /**
     * 测试资源2
     * @param session * @return
     */
    @GetMapping(value = "/r/r2")
    public String r2(HttpSession session){
        String fullname = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if(userObj != null){
            fullname = ((UserDto)userObj).getFullname();
        }else{
            fullname = "匿名"; }
        return fullname + " success 2"; }
}
